import React, { useState, useRef, useEffect } from 'react';
import { SearchOutlined, FilterOutlined, DownOutlined, EyeOutlined, DeleteOutlined } from '@ant-design/icons';
import { Button, Input, Space, Table, Radio, Popconfirm, Select, Tooltip, Dropdown, Divider } from 'antd';
import Highlighter from 'react-highlight-words';
import { useHistory } from 'react-router-dom';
import RcViewer from '@hanyk/rc-viewer';
import { Resizable } from 'react-resizable';
import 'react-resizable/css/styles.css';

import { useLatest } from 'ahooks';
import { Editor } from 'tinymce';
const { Search } = Input;
var storage = window.localStorage;

// 可伸缩的表头组件
const ResizableTitle = props => {
  const { onResize, width, onResizeStop, ...restProps } = props;

  if (!width) {
    return <th {...restProps} />;
  }

  return (
    <Resizable
      width={width}
      height={0}
      handle={
        <span
          className="react-resizable-handle"
          onClick={e => e.stopPropagation()}
          style={{
            position: 'absolute',
            right: -5,
            bottom: 0,
            top: 0,
            width: 10,
            cursor: 'col-resize'
          }}
        />
      }
      onResize={onResize}
      onResizeStop={onResizeStop}
      draggableOpts={{ enableUserSelectHack: false }}
    >
      <th {...restProps} />
    </Resizable>
  );
};

/**
 * 
 * @param {Object} showCz  操作区对象  showCz.showEdit 是否显示编辑 showCz.showView 是否显示查看 showCz.showDelete 是否显示删除
 * @param {Number} czWidth  操作区的宽度 默认120
 * @param {function} handleEdit  编辑或查看的回调方法
 * @param {function} handleDelete  删除的回调方法
 * @param {function} renderCz  操作区的渲染组件 
 * @param {function} handleView  查看的回调方法
 * @param {function} rowCz  行操作条件 返回一个对象，对象的key为操作名，value为操作的回调方法 传了rowCz则showCz无效
 * 例子：
 * rowCz={(record) => {
 *   if (record.SubTableCount > 0) {
 *     return {
 *       showView: true,
 *     }
 *   }
 *   else {
 *     return {
 *       showEdit: true,
 *     }
 *   }
 * }}
 * @param {Object} czMaps  操作区的map对象   例子 cz为操作名 handle 为操作的回调方法 且需要传进来，不传则默认为 
 * czMaps={
      showEdit: { cz: '编辑', handle: props.handleEdit },
      showDelete: { cz: '删除', handle: props.handleDelete },
      showView: { cz: '查看', handle: props.handleView },
    }
 * @returns 
 */

const ResizableTable = (props) => {
  const history = useHistory();
  const [selectionType, setSelectionType] = useState(props.selecttype ? props.selecttype : 'checkbox');
  const [searchText, setSearchText] = useState('');
  const [searchedColumn, setSearchedColumn] = useState('');
  const searchInput = useRef(null);
  const [selectedRows, setselectedRows] = useState([])
  const [selectedRowKeys, setselectedRowKeys] = useState([])
  const [currentdatas, setcurrentdatas] = useState([])
  const [isExactMatch, setIsExactMatch] = useState(false);
  const [columns, setColumns] = useState([]);
  const columnsRef = useLatest(columns);

  const isExactMatchRef = useLatest(isExactMatch);
  useEffect(() => {
    setColumns(
      props.tablecolnum.filter(item => item.show == true).map((item) => ({
        ...item,
        dataIndex: item.key,
        onHeaderCell: column => ({
          width: column.width,
          onResize: handleResize(item.key),
          onResizeStop: handleResizeStop(item.key),
        }),
        ...getColumnSearchProps(item.key, item.style, item.rendertype, item.ifcolor, item.title, item.searchtype),
      }))
    )
  }, [props.tablecolnum])
  // rowSelection object indicates the need for row selection
  const rowSelection = {
    selectedRowKeys: props.selectedRowKeys,
    onChange: (selectedRowKeys, selectedRows) => {
      props.handleselectson(selectedRows, selectedRowKeys)

    },
    getCheckboxProps: (record) => ({
      disabled: record.name === 'Disabled User',
      // Column configuration not to be checked
      name: record.name,
    }),
    selections: [
      Table.SELECTION_ALL,
      Table.SELECTION_INVERT,
      Table.SELECTION_NONE]
  };

  const handleSearch = (selectedKeys, confirm, dataIndex) => {
    confirm();
    setSearchText(selectedKeys[0]);
    setSearchedColumn(dataIndex);
    setIsExactMatch(false);
  };
  const handleSearchExact = (selectedKeys, confirm, dataIndex) => {
    confirm();
    setSearchText(selectedKeys[0]);
    setSearchedColumn(dataIndex);
    setIsExactMatch(true);
  };
  const handleReset = (clearFilters) => {
    clearFilters();
    setSearchText('');
  };

  //row双击s
  const onRowSelect = (record, index) => {
    return {
      onDoubleClick: (e) => {

        if (props.sfdoubleclick) {
          storage[props.storagekey] = JSON.stringify(record)
          history.push({ pathname: props.doubleclickroute });
        } else;
      }
    }
  };

  const handleResize = (dataIndex) => (e, { size }) => {
    setColumns(prevColumns => {
      return prevColumns.map(col => {
        if (col.dataIndex === dataIndex) {
          return {
            ...col,
            width: size.width,
          };
        }
        return col;
      });
    });
  };

  const handleResizeStop = (key) => (e, { size }) => {
    // console.log(columnsRef.current, "columnsRef");
    storage[props.storageName] = JSON.stringify(columnsRef.current.filter(item => item.dataIndex != "action"))
  };

  const components = {
    header: {
      cell: ResizableTitle,
    },
  };

  //改为下拉框搜索模式

  const getColumnSearchProps = (dataIndex, style, rendertype, ifcolor, title, searchtype) => ({
    filterDropdown: ({ setSelectedKeys, selectedKeys, confirm, clearFilters, close }) => (
      <div
        style={{
          padding: 16,
        }}
        onKeyDown={(e) => e.stopPropagation()}
      >
        {
          //根据类型选择input、select或list列表模式

          searchtype == "select" ?

            <Select
              ref={searchInput}
              mode="multiple"
              showSearch
              placeholder={`搜索${title}`}
              onChange={(value) => setSelectedKeys(value)}
              onSearch={(value) => setSelectedKeys(value ? [value] : [])}
              onClear={() => {
                setSelectedKeys([]);
                clearFilters();
              }}
              allowClear
              style={{
                width: '20vw',
                marginBottom: 8,
                display: 'block',
              }}
            >
              {[...new Set(props.tabledata.map(item => item[dataIndex]))].map((value) => (
                <Select.Option key={value} value={value}>
                  {value}
                </Select.Option>
              ))}
            </Select>
            :
            <Input
              ref={searchInput}
              placeholder={`搜索${title}`}
              value={selectedKeys[0]}
              onChange={(e) => setSelectedKeys(e.target.value ? [e.target.value] : [])}
              onPressEnter={() => handleSearch(selectedKeys, confirm, dataIndex)}
              style={{
                marginBottom: 8,
                display: 'block',
              }}
            />
        }

        <Space>
          <Button
            type="primary"
            onClick={() => handleSearch(selectedKeys, confirm, dataIndex)}
            icon={<SearchOutlined />}
            size="small"
            style={{
              width: 90,

            }}
          >
            搜索
          </Button>
          <Button
            type="primary"
            onClick={() => handleSearchExact(selectedKeys, confirm, dataIndex)}
            icon={<SearchOutlined />}
            size="small"
            style={{
              width: 90,
            }}
          >
            精准搜索
          </Button>
          <Button
            onClick={() => clearFilters && handleReset(clearFilters)}
            size="small"
            style={{
              width: 90,
            }}
          >
            重置
          </Button>
          <Button
            type="link"
            size="small"
            style={{ color: "#0885fb" }}
            onClick={() => {
              confirm({
                closeDropdown: false,
              });
              setSearchText(selectedKeys[0]);
              setSearchedColumn(dataIndex);
            }}
          >
            过滤
          </Button>
          <Button
            type="link"
            size="small"
            style={{ color: "#0885fb" }}
            onClick={() => {
              close();
            }}
          >
            关闭
          </Button>
          {/* <Checkbox onChange={(e)=>{setIsExactMatch(e.target.checked)}} value={isExactMatch}>精准匹配</Checkbox> */}
        </Space>
      </div>
    ),
    filterIcon: (filtered) => (
      searchtype == "select" ?
        <FilterOutlined
          style={{
            color: filtered ? '#f0721f' : '#0885fb',
          }}
        />
        :
        <SearchOutlined
          style={{
            color: filtered ? '#f0721f' : '#0885fb',
          }}
        />
    ),
    onFilter: (value, record) => {
      if (searchtype == "select") {
        return record[dataIndex].toString().toLowerCase() == value.toString().toLowerCase()
      } else if (isExactMatchRef.current) {
        return record[dataIndex].toString().toLowerCase() == value.toString().toLowerCase()
      } else {
        return record[dataIndex].toString().toLowerCase().includes(value.toLowerCase())
      }
    },
    onFilterDropdownOpenChange: (visible) => {
      if (visible) {
        setTimeout(() => searchInput.current ? searchInput.current.select() : 1, 100);
      }
    },
    render: (text) => {
      const renderContent = (text, rendertype) => {
        // 处理图片渲染
        if (rendertype === "img") {
          if (!text || text === "null") {
            return (
              <div style={{ color: props.calcolor ? props.calcolor(text) : "black" }}>
                <span style={{ color: "gray" }}>无图片</span>
              </div>
            );
          }

          return (
            <div style={{ color: props.calcolor ? props.calcolor(text) : "black", display: "flex", flexDirection: "row" }}>
              <RcViewer options={{ toolbar: 1 }}>
                {text.split(',').map((item, index) => (
                  <div key={index} style={{ width: "4vw", height: "4vw", position: 'relative', marginLeft: "0.1vw", display: "inline-block" }}>
                    <img
                      style={{ width: "90%", left: "0", position: "absolute", right: "0", top: "0", bottom: "0", margin: "auto" }}
                      src={`http://111.77.154.58:2233/${item}`}
                      alt=""
                    />
                  </div>
                ))}
              </RcViewer>
            </div>
          );
        }

        // 处理URL渲染
        if (rendertype === "url") {
          if (!text || text === "null") {
            return (
              <div style={{ color: props.calcolor ? props.calcolor(text) : "black" }}>
                <span style={{ color: "gray" }}>无附件</span>
              </div>
            );
          }

          return (
            <div style={{ color: props.calcolor ? props.calcolor(text) : "black" }}>
              {text.split(',').map((item, index) => (
                <div key={index} style={{ position: 'relative' }}>
                  <a
                    style={{ color: "#0885fb" }}
                    href={`http://111.77.154.58:2233/${item}`}
                    target="_blank"
                    rel="noopener noreferrer"
                  >
                    附件{index + 1}
                  </a>
                </div>
              ))}
            </div>
          );
        }

        // 处理普通文本渲染
        if (searchedColumn === dataIndex) {
          return (
            <Highlighter
              highlightStyle={{
                backgroundColor: '#ffc069',
                padding: 0,
              }}
              searchWords={[searchText]}
              autoEscape
              textToHighlight={text ? text.toString() : ''}
            />
          );
        }

        return (
          <span style={{ color: props.calcolor ? props.calcolor(text) : "black" }}>
            <Tooltip title={text}>
              <span style={style ? style : {}}>{text}</span>
            </Tooltip>
          </span>
        );
      };

      return renderContent(text, rendertype);

    },

  });
  //操作区组件
  const CzItems = (czProps) => {
    // console.log(props.czMaps, "props.czMaps");
    let czMaps = {}
    if (props.czMaps) {
      for (var key in props.czMaps) {
        czMaps[key] = { cz: props.czMaps[key].cz, handle: props[props.czMaps[key].handle] }
      }
    } else {
      czMaps = {
        showEdit: { cz: '编辑', handle: props.handleEdit },
        showDelete: { cz: '删除', handle: props.handleDelete },
        showView: { cz: '查看', handle: props.handleView },
      }
    }
    if (czProps.rowCz) {
      // console.log(czProps.rowCz(czProps.record), "czProps.rowCz");
      let keys = Object.keys(czProps.rowCz(czProps.record))
      // 根据props.showCz的值的数量，生成相应的items，一个就直接显示，多个就生成一个下拉框
      if (keys.length == 1) {
        return keys.map(key => (
          // <Popconfirm title={`要${czMaps[key].cz}单据吗？`} onConfirm={() => czMaps[key].handle(czProps.record)}>
            <a key={key} onClick={() => czMaps[key].handle(czProps.record)} style={{ fontSize: '0.75rem', color: '#1890ff', backgroundColor: 'transparent', cursor: 'pointer' }} >{czMaps[key].cz}</a>
          // </Popconfirm>
        ))
      } else if (keys.length > 1) {
        return <>
          {/* <Popconfirm title={`要${czMaps[keys[0]].cz}单据吗？`} onConfirm={() => czMaps[keys[0]].handle(czProps.record)}> */}
            <a key="1" onClick={() => czMaps[keys[0]].handle(czProps.record)} style={{ fontSize: '0.75rem', color: '#1890ff', backgroundColor: 'transparent', cursor: 'pointer' }} >
              {czMaps[keys[0]].cz}
            </a>
          {/* </Popconfirm> */}
          <Divider type="vertical" />
          <Dropdown
            menu={{
              items: keys.map((key, index) => (index > 0 ? {
                key: key,
                label: <a onClick={() => czMaps[keys[index]].handle(czProps.record)} style={{ fontSize: '0.75rem', color: '#1890ff', backgroundColor: 'transparent', cursor: 'pointer' }} >{czMaps[keys[index]].cz}</a>
                // <Popconfirm title={`要${czMaps[keys[index]].cz}单据吗？`} onConfirm={() => czMaps[keys[index]].handle(czProps.record)}>
                  
                // </Popconfirm>
              } : ''))
            }}
          >
            <a onClick={(e) => e.preventDefault()} style={{ fontSize: '0.7rem', color: '#1890ff', backgroundColor: 'transparent', cursor: 'pointer' }}>
              <Space>
                更多
                <DownOutlined />
              </Space>
            </a>
          </Dropdown>
        </>
      } else {
        return ''
      }
    } else {
      if (czProps.showCz) {
        let keys = Object.keys(czProps.showCz)
        // 根据props.showCz的值的数量，生成相应的items，一个就直接显示，多个就生成一个下拉框
        if (keys.length == 1) {
          return keys.map(key => (
            // <Popconfirm title={`要${czMaps[key].cz}单据吗？`} onConfirm={() => czMaps[key].handle(czProps.record)}>
              <a key={key} onClick={() => czMaps[key].handle(czProps.record)} style={{ fontSize: '0.75rem', color: '#1890ff', backgroundColor: 'transparent', cursor: 'pointer' }} >{czMaps[key].cz}</a>
            // </Popconfirm>
          ))
        } else if (keys.length > 1) {
          return <>
            {/* <Popconfirm title={`要${czMaps[keys[0]].cz}单据吗？`} onConfirm={() => czMaps[keys[0]].handle(czProps.record)}> */}
              <a key="1" onClick={() => czMaps[keys[0]].handle(czProps.record)} style={{ fontSize: '0.75rem', color: '#1890ff', backgroundColor: 'transparent', cursor: 'pointer' }} >
                {czMaps[keys[0]].cz}
              </a>
            {/* </Popconfirm> */}
            <Divider type="vertical" style={{ height: "1.8vw" }} />
            <Dropdown
              menu={{
                items: keys.map((key, index) => (index > 0 ? {
                  key: key,
                  label: <a onClick={() => czMaps[keys[index]].handle(czProps.record)} style={{ fontSize: '0.75rem', color: '#1890ff', backgroundColor: 'transparent', cursor: 'pointer' }} >{czMaps[keys[index]].cz}</a>
                  // </Popconfirm>
                } : ''))
              }}
            >
              <a onClick={(e) => e.preventDefault()} style={{ fontSize: '0.7rem', color: '#1890ff', backgroundColor: 'transparent', cursor: 'pointer' }}>
                <Space>
                  更多
                  <DownOutlined />
                </Space>
              </a>
            </Dropdown>
          </>
        } else {
          return ''
        }
      }
    }
  }

  props.showCz && Object.keys(props.showCz).length > 0 && columns.filter(item => item.key == "action").length == 0 ?
    columns.push({
      title: '操作',
      dataIndex: 'action',
      fixed: "right",
      width: props.czWidth ? props.czWidth : 120,
      key: 'action',
      render: (text, record) => (
        props.renderCz ? props.renderCz(record) :
          <div style={{ width: "100%", display: "flex", justifyContent: "space-around" }}>
            <CzItems record={record} showCz={props.showCz} rowCz={props.rowCz} />
          </div>
      )
    }) : ''

  return (
    <div style={{ position: "relative", height: "", width: props.width ? props.width : "100%" }}>
      <Radio.Group style={{ display: props.ifhiddencchangeselecttype ? "none" : "block" }}
        onChange={({ target: { value } }) => {
          setSelectionType(value);
        }}
        value={selectionType}
      >
        <Radio value="checkbox">多选</Radio>
        <Radio value="radio">单选</Radio>
      </Radio.Group>

      {
        props.title ? (<Table columns={columns} dataSource={props.tabledata} style={{
          width: "98%", minHeight: "20vh", marginRight: "1%"
        }}
          title={() => { return <div style={{ fontWeight: "800" }}>{props.title}</div> }}
          size="small"
          pagination={{
            defaultPageSize: props.defaultPageSize ? props.defaultPageSize : 20
            , total: currentdatas.length, pageSizeOptions: ['15', '30', '50', '110'], position: ['bottomLeft']
          }}
          bordered={props.bordered ? props.bordered : false}
          onRow={onRowSelect}
          scroll={props.scroll ? props.scroll : false}
          rowSelection={{
            type: selectionType,
            ...rowSelection,
          }} />)
          :
          (<Table columns={columns} dataSource={props.tabledata} style={{
            width: "98%", marginRight: "1%", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis"
          }}
            size="small"
            pagination={{
              defaultPageSize: props.defaultPageSize ? props.defaultPageSize : 20,
              total: currentdatas.length, pageSizeOptions: ['15', '30', '50', '110', '200', '500'],
              position: ['bottomLeft']
            }}
            expandable={props.expandable ? props.expandable : {}}
            bordered={props.bordered ? props.bordered : false}
            scroll={props.scroll ? props.scroll : false}
            onChange={(pagination, filters, sorter, extra) => {
              setcurrentdatas(extra.currentDataSource)
            }}
            rowClassName={props.rowClassName ? (record, index) => { return props.rowClassName(record, index) } : ''}
            components={components}
            onRow={onRowSelect}
            rowSelection={{
              type: selectionType,
              ...rowSelection,
            }} />)
      }

    </div>)

}

export default ResizableTable

var styles = {
  maincontainer: { height: "90%", width: "99%", backgroundColor: `#F1F1F1`, }
}